from werkzeug.utils import secure_filename
from .aliyunVideo import *
from datetime import datetime
import os, json, random, string, traceback, base64
from flask import current_app


# 检测是否为允许的视频文件
def allowed_video_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower(
           ) in current_app.config['ALLOWED_VIDEO_EXTENSIONS']


# 检测是否为允许的文件
def allowed_image_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower(
           ) in current_app.config['ALLOWED_IMAGE_EXTENSIONS']

# 生成随机字符串
def random_string(slen=8):
    return ''.join(random.sample(string.ascii_letters + string.digits, slen))


def saveImg(request, IMAGES_UPLOAD_FOLDER, remoteFileName='photo'):
    imgUrl = None
    # 图片检验
    # 若无lovePostPhoto文件名或文件名不对，则传递参数有误
    if remoteFileName not in request.files:
        message = "No file part"
        status_code = 400
        return imgUrl, message, status_code
    
    photo = request.files[remoteFileName]

    # 若传递的文件其名为空，则未选择文件
    if photo.filename == '':
        message = 'No selected file'
        status_code = 400
        return imgUrl, message, status_code

    # 若文件有内容且在允许上传的文件类型中，则实施上传
    if photo and allowed_image_file(photo.filename):
        filename = datetime.now().strftime('%Y%m%d%H%M%S_') + random_string() + \
            '_' + secure_filename(photo.filename)
        photo.save(os.path.join(IMAGES_UPLOAD_FOLDER, filename))
        imgUrl = "http://39.106.98.248/image/" + filename
        message = 'success'
        status_code = 200  
    else:
        # 不允许的上传文件类型
        message = 'No allow upload file type!'
        status_code = 403

    return imgUrl, message, status_code
    